import api from '../../../api/index';
import dayjs from '../../../plugin/dayjs/index';
import daysbefore from '../../../plugin/daysbefore';
import * as echarts from '../../../components/ec-canvas/echarts';
import bleUtils from '../../utils/bluetooth'


//全局声明chart
var seriesDataArr = [];
var timeArr = [];
var chart = null;

// 时间格式化
function formatTime(date = new Date()) {
	return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
}
function formatTime2(date = new Date()) {
	return dayjs(date).format('YYYY-MM-DD');
}
Component ({
	properties: {
	},
	/**
   * 页面的初始数据
   */
	data: {
		inputshow: false,
		inputlist: [
			{ unit: 'mmHg', value: '', text: '请输入收缩压' },
			{ unit: 'mmHg', value: '', text: '请输入舒张压' },
			{ unit: '次/分', value: '', text: '请输入心率' }
		],
		c_val: 80,
		shebeiicon: 'http://lk-webfont.oss-cn-beijing.aliyuncs.com/redstart/%E8%A1%80%E5%8E%8B.png',
		fasleshebeiicon: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/sportsAdministration/gantanhao.png',

		hartValue: '',
		upValue: '',
		downValue: '',
		linedata: null,
		show: false,
		showDialog: false,
		bindDeviceTextInfo: '',
		ec: {
			// 初始化图表
			onInit: (canvas, width, height) => {
				//初始化echarts元素，绑定到全局变量，方便更改数据
				chart = echarts.init(canvas, null, {
					width: width,
					height: height
				});
				canvas.setChart(chart);
				return chart;
			}
		},
		bindDeviceId: null,
		gyValue: '--',
		dyValue: '--',
		pluseValue: '--',
	},

	/**
   * 生命周期函数--监听页面加载
   */
  ready: function() {
		// this.drawProgress()
		this.gethistrorylist(); //查看历史数据
		this.getloadlist(); //查询当前最新数据
		this.doInitBlue()
	},
	methods: {
		openkpxt() {
			wx.navigateTo({
				url: `/blood/pages/tnb-bzkp/index`,
			  })
		   },
		   openKt() {
			wx.navigateTo({
				url: `/blood/pages/tnb-bzkp/index`,
			  })
			},
			gohistorypage() {
				wx.navigateTo({
					url: `/blood/pages/history/index`,
				  })
			},
			async get() {
				try {
				  const res = await api.post('/api/user/storage/get', {
					data: {
					  'key': 'devicelist'
					}
				  })
				  if(res[0].value) {
						var array = JSON.parse(res[0].value)
						const listValue = array.filter(item => item.name === 'blood')
						if(listValue.length > 0) {
							this.bindEquipment(listValue[0].devicelist[0].deviceId)
						}
				  }
				} catch (e) {
				  console.log('get->', e)
				  return null
				}
			},
				// 蓝牙初始化
  doInitBlue() {
    bleUtils.initBlueTooth().then((res) => {
      this.doGetBluetoothAdapterState()
			this.get()
    })
  },
  // 获取蓝牙适配器状态
  doGetBluetoothAdapterState() {
    bleUtils.getBluetoothAdapterState().then((res) => {
    })
  },
  //开始搜索蓝牙设备
  doStartSearchBlueTooth() {
    bleUtils.startSearchBlueTooth().then((res) => {
      this.doOnBluetoothDeviceFound()
    })
  },
  // 监听搜素到新的蓝牙设备
  doOnBluetoothDeviceFound() {
    bleUtils.onBluetoothDeviceFound().then((res) => {
			const filterValue = res.filter(item => item.name === 'Belter_BT')
			if(filterValue.length > 0) {
				this.setData({
					bindDeviceId: filterValue[0].deviceId
				})
				// 搜索到可用的蓝牙设备，停止搜索
				bleUtils.stopSearchBlueTooth()
				this.bindEquipment(filterValue[0].deviceId)
			} else {
				//没有搜索到可用设备，重新搜索
				console.log('没有搜索到可用设备，重新搜索')
				// this.doStartSearchBlueTooth()
				this.setData({
					bindDeviceTextInfo: '没有搜索到对应的蓝牙设备，请重新搜索'
				})
				setTimeout(() => {
					this.setData({
						showDialog: false
					})
				}, 1500);
			}
    })
  },
	// 连接蓝牙设备
  bindEquipment(deviceId) {
		this.setData({
			bindDeviceId: deviceId
		})
		this.setData({
			bindDeviceTextInfo: '连接设备中...'
		})
		this.setData({
			showDialog: true
		})
    bleUtils.createBLEConnection(this.data.bindDeviceId).then((res) => {
      console.log(res, '连接成功')
			this.setData({
				bindDeviceTextInfo: '链接设备成功，正在测量中'
			})
      this.doGetBLEDeviceServices()
    }).catch(err => {
      console.log(err, '连接设备失败')
      this.doGetBLEDeviceServices()
    })
  },
	onCancel() {
		this.setData({
			showDialog: false,
		})
		// 停止搜索
		bleUtils.stopSearchBlueTooth()
	},
	// 获取蓝牙设备特征值
  doGetBLEDeviceServices(bindDeviceId) {
    bleUtils.getBLEDeviceServices(this.data.bindDeviceId).then(res => {
			if (res.success) {
				this.setData({
					bindDeviceTextInfo: '测量结束'
				})
				setTimeout(() => {
					this.setData({
						showDialog: false
					})
				}, 500);
				this.setData({
					gyValue: res.gy,
					dyValue: res.dy,
					pluseValue: res.pluse,
				})
				this.setData({
					'inputlist[0].value': parseInt(res.gy)
				});
				this.savedevices()
			} else {
				this.setData({
					bindDeviceTextInfo: '测量出错，请重新测量'
				})
				setTimeout(() => {
					this.setData({
						showDialog: false,
					})
				}, 500);
			}
		})
  },
	getWeekDays() {
		let dates = []
		for (var i = 365; i >= 0; i--) {
			var currentDate = new Date();
			currentDate.setDate(currentDate.getDate() - i);
			var month = ("0" + (currentDate.getMonth() + 1)).slice(-2);
			var day = ("0" + currentDate.getDate()).slice(-2);
			var formattedDate = month + "/" + day;
			dates.push(formattedDate);
		}
		return dates
	},
	gethistrorylist() {
		api
			.post('/api/hxhealth/exams/records', {
				data: {
					everyday: true,
					itemcode: 'XYZBXY001008',
					typecode: '',
					everyday: true
				},
				head: {
					firstresult: 0,
					maxresults: 1000,
					bodytype: 'flat',
				}
			})
			.then((res) => {
				// console.log(res);
				console.log('----历史数据----', res);
				if (res.length > 0) {
					const jsonData = res;
					// 提取数据的数组
					const values1 = [];
					const times = [];

					// 遍历 body 数组
					jsonData.forEach((entry) => {
						// 遍历 devices 数组
						entry.devices.forEach((device) => {
							console.log(device);
							// 找到 code 为 "XYZBXY001008" 的项
							const item1 = device.items.find((item) => item.code === 'XYZBXY001008');
							times.push(entry.time.slice(0, 10).replace(/-/g, '/'));

							// 如果找到了，将 value 和 time 添加到相应的数组中
							if (item1) {
								values1.push(Number(item1.value)); // 将值转换为数字类型
							} else {
								values1.push(null); 
							}
						});
					});
					const linedata = {
						values1,
						times
					};
					console.log(linedata, 'linedata');
					this.setData({
						linedata
					});
					// 模拟获取接口数据
					setTimeout(() => {
						this.getEchartData(linedata);
					}, 1000);
				} else {
					const linedata = {
						values: [],
						times: this.getWeekDays()
					};
					this.setData({
						linedata
					});
					// 模拟获取接口数据
					setTimeout(() => {
						this.getEchartData(linedata);
					}, 1000);
				}
			});
	},
	getloadlist() {
		// 整体列表查询
		api
			.post('/api/exams/lastvalues', {
				data: {
					devkind: '',
					devmode: '',
					itemcode: '',
					typecode: 'threeinoneequip',
					unionuser: true
				}
			})
			.then((res) => {
				// console.log(res);
				console.log('----最新数据----', res);
				const array = res;
				this.setData({
					newtime: res[0].examtime
				});
				for (let y = 0; y < array.length; y++) {
					
					if (array[y].code == 'XYZBXY001008') {
						this.setData({
							downValue: parseInt(array[y].value).toFixed(1)
						});
					}
				}
			});
	},
	savedevices() {
		console.log('2222');
		let data = {
			name: '血糖监测',
			time: formatTime(),
			typecode: 'bloodpmeter',
			typename: '血糖监测',
			devices: [
				{
					name: '血糖监测',
					kind: 'bloodpmeter',
					items: [
						{
							code: 'XYZBXY001008',
							checkDate: null,
							level: null,
							value: parseInt(this.data.inputlist[0].value),
							deviceBrand: '',
							deviceNo: ''
						}
					]
				}
			]
		};
		// 整体列表查询
		api
			.post('/api/hxhealth/exams/save', {
				data
			})
			.then((res) => {
				// console.log(res);
				console.log('----保存录入----', res);
				this.getloadlist();
				this.closesaveNickname();
				wx.showToast({
					icon: 'none',
					title: '保存成功'
				});
			})
			.catch((e) => {
				console.log(e);
				wx.showToast({
					icon: 'none',
					title: e.faultstring ? e.faultstring : '保存失败'
				});
			});
	},
	openNickname() {
		this.setData({
			inputshow: true
		});
	},
	closesaveNickname() {
		this.setData({
			inputshow: false
		});
	},
	userNameInput1(e) {
		console.log(e.detail.value);
		this.setData({
			'inputlist[0].value': e.detail.value
		});
	},
	userNameInput2(e) {
		console.log(e.detail.value);
		this.setData({
			'inputlist[1].value': e.detail.value
		});
	},
	userNameInput3(e) {
		console.log(e.detail.value);
		this.setData({
			'inputlist[2].value': e.detail.value
		});
	},
	saveNickname() {
		let cansave = true
		this.data.inputlist.forEach(item => {
			if(!item.value) {
				wx.showToast({
					title: '请输入数值',
					icon: 'none',
					duration: 2000
				})
				cansave = false
				return
			}
			if(!/^\d+$/.test(Number(item.value))) {
				wx.showToast({
					title: '请输入正整数',
					icon: 'none',
					duration: 2000
				})
				cansave = false
				return
			}
		})
		if(cansave) {
			this.savedevices();
		}
	},
	modal_click_Hidden() {
		this.setData({
			inputshow: false
		});
	},
	openkp() {
		wx.navigateTo({
      url: `/blood/pages/bzkp/index`,
    })
	},
	openKy() {
		wx.navigateTo({
      url: `/blood/pages/kyfa/index`,
    })
	},
	// 绘制图表
	runColumncCanva() {
		var option = {
			title: {
				// text: '次/分',
				textStyle: {
					fontSize: 9,
					color: '#666666'
				}
			},
			color: ['#37A2DA'],
			legend: {
				data: [ '血糖' ],
				icon: 'circle',
				left: 0,
				itemWidth: 9,
				// itemStyle: {
				//     color: '#5BBF70'
				// },
				textStyle: {
				    color: '#333333',
				    fontSize: 20
				}
			},
			grid: {
				left: '0%',
				right: '5%',
				bottom: 0,
				top: '15%',
				containLabel: true,
				show: true
			},

			tooltip: {
				show: true,
				trigger: 'axis'
			},
			xAxis: {
				type: 'category',
				boundaryGap: false,
				data: timeArr,
				axisLabel: {
					fontSize: 16,
					rotate: 0 //倾斜度 -90 至 90 默认为0
				}
			},
			yAxis: {
				type: 'value',
				splitLine: {
					lineStyle: {
						type: 'dashed'
					}
				},
				axisLabel: {
					fontSize: 16
				}
			},
			series: seriesDataArr
		};
		//这里一定要做个charts是否存在的判断，因为万一ec那里没有初始化，这里就会报错
		if (chart) {
			chart.setOption(option);
			this.setData({
				show: true
			});
		}
	},
	getEchartData(linedata) {
		seriesDataArr = [
			{
				name: '血糖',
				type: 'line',
				smooth: true,
				data: linedata.values1,
				connectNulls: true
			}
		];
		timeArr = linedata.times;
		this.runColumncCanva();
	},
	// 链接设备
	goBindEq() {
		// this.setData({
		// 	bindDeviceTextInfo: '正在搜索蓝牙设备'
		// })
		// this.setData({
		// 	showDialog: true
		// })
		// this.doStartSearchBlueTooth()
		wx.navigateTo({
			url: '/blood/pages/measurement/index'
		});
	},
},
	/**
   * 生命周期函数--监听页面初次渲染完成
   */
	onReady: function() {},

	/**
   * 生命周期函数--监听页面显示
   */
	onShow() {},

	/**
   * 生命周期函数--监听页面隐藏
   */
	onHide() {},

	/**
   * 生命周期函数--监听页面卸载
   */
	onUnload() {
		this.closeBLE(this.data.bindDeviceId)
	},

	/**
   * 页面相关事件处理函数--监听用户下拉动作
   */
	onPullDownRefresh() {},

	/**
   * 页面上拉触底事件的处理函数
   */
	onReachBottom() {},

	/**
   * 用户点击右上角分享
   */
	onShareAppMessage() {}
});
